<template>
  <div class="friend-wrap">
    <div class="friend-box" v-if="!$common.isEmpty(store.id)">
      <div class="friend-bode" id="body-group">
        <div class="body-left" v-show="showBodyLeft">
          <!-- 搜索 -->
          <div>
            <n-input v-model:value="showFriendValue" round placeholder="搜索" class="im-input"></n-input>
          </div>
          <!-- 聊天 -->
          <div class="aside-list" v-show="type === 1">
            <div class="im-user im-active" @click="isActive($event, 'im-active', null, 1);handleAdd">
              <div>
                <svg viewBox="0 0 1024 1024" width="40" height="40">
                  <path d="M0 0h1024v1024H0V0z" fill="#202425" opacity=".01" p-id="5899"></path>
                  <path d="M512 102.4a68.266667 68.266667 0 0 1 68.266667 68.266667v273.066666h273.066666a68.266667 68.266667 0 1 1 0 136.533334h-273.066666v273.066666a68.266667 68.266667 0 1 1-136.533334 0v-273.066666H170.666667a68.266667 68.266667 0 1 1 0-136.533334h273.066666V170.666667a68.266667 68.266667 0 0 1 68.266667-68.266667z" fill="#FF7744" p-id="5900"></path>
                </svg>
              </div>

              <div class="im-user-right" style="align-self: center">
                <div @click="handleAdd">新建会话</div>
              </div>
            </div>


            <!-- 聊天 -->
            <div class="im-user im-user-current"
                 v-for="(item, index) in aiChatConversationList"
                 :key="index"
                 :class="{'is-active-chat':item == currentAiChatConversation}"
                 v-show="!$common.isEmpty(friends[item])?friends[item].remark.includes(showFriendValue) || $common.isEmpty(showFriendValue):true"
                 @click="isActive($event, 'im-active', null, 2, item, 2)">
              <div>
                <n-badge :value="imMessageBadge[item]" :max="99">
                  <n-avatar object-fit="cover"
                            :size="40"
                            :src="aiCover"/>
                  </n-badge>
              </div>
              <div class="im-user-right" style="align-self: center">
                <div>
                  {{item.title}}</div>
<!--                <div class="im-down" v-if="!$common.isEmpty(aiChatMessageList[item])">-->
<!--                  {{aiChatMessageList[item][aiChatMessageList[item].length-1].content.substr(0, 8)}}-->
<!--                </div>-->
              </div>
            </div>
          </div>
        </div>
        <div class="body-right" v-if="subType === 1">
          <div style="height: 60px;background-color: var(--maxWhite)">
            <span style="line-height: 60px;margin-left: 20px;font-size: 18px">系统消息</span>
          </div>
          <div style="background: var(--midWhite);overflow-y: scroll;height: calc(100% - 60px);">
            <div class="msg-one"
                 v-for="(item, index) in systemMessages"
                 :key="index">
              <!-- 图标 -->
              <div>
                <svg viewBox="0 0 1024 1024" width="50" height="50">
                  <path
                    d="M752.768 955.392H257.92c-112.384 0-203.392-91.008-203.392-203.392V257.152C54.528 144.768 145.536 53.76 257.92 53.76h494.848C865.152 53.76 956.16 144.768 956.16 257.152v494.848c0 112.384-91.008 203.392-203.392 203.392z"
                    fill="#FF4D3C"></path>
                  <path
                    d="M616.576 765.952H370.56c-67.968 0-123.008-55.04-123.008-123.008V396.8c0-67.968 55.04-123.008 123.008-123.008h166.272c9.984 0 18.176 8.064 18.176 18.176 0 9.984-8.064 18.176-18.176 18.176H370.56c-47.872 0-86.656 38.784-86.656 86.656v246.016c0 47.872 38.784 86.656 86.656 86.656h246.016c47.872 0 86.656-38.784 86.656-86.656V469.12c0-9.984 8.064-18.176 18.176-18.176 9.984 0 18.176 8.064 18.176 18.176v173.824c0 67.968-55.04 123.008-123.008 123.008z"
                    fill="#FFFFFF"></path>
                  <path d="M694.784 312.704m-113.408 0a113.408 113.408 0 1 0 226.816 0 113.408 113.408 0 1 0-226.816 0Z"
                        fill="#FFFFFF"></path>
                </svg>
              </div>

              <!-- 内容 -->
              <div style="margin-left: 10px">
                <div class="system-date">
                  {{item.createTime}}
                </div>
                <div class="system-content">
                  {{item.content}}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天 -->
        <chat class="body-right"
              :key="currentAiChatConversation.id"
              v-if="subType === 2 && (!$common.isEmpty(currentAiChatConversation) )"
              :currentAiChatConversation="currentAiChatConversation"
              @sendMsg="sendMsg"
              @openFriendCircle="openFriendCircle"></chat>



        <div class="body-right" v-if="subType === 4 && !$common.isEmpty(currentFriendId)">
          <div style="height: 60px;background-color: var(--maxWhite)">
            <span style="line-height: 60px;margin-left: 20px;font-size: 18px">
              {{friends[currentFriendId].remark}}
            </span>
          </div>
          <div style="background: var(--midWhite);height: calc(100% - 60px)">
            <div class="myCenter">
              <div class="friend-info">
                <div style="display: flex;align-items: center">
                  <n-avatar object-fit="cover"
                            :size="60"
                            :src="friends[currentFriendId].avatar"/>

                  <span style="margin: 0 5px 0 15px;font-size: 16px">{{friends[currentFriendId].remark}}</span>
                  <span style="cursor: pointer;margin-top: 6px" @click="changeDataType(1)">
                    <svg viewBox="0 0 1024 1024" width="20" height="20">
                      <path
                        d="M929.909189 827.019236H93.990821c-16.598379 0-29.997071 13.398692-29.99707 29.997071s13.398692 29.997071 29.99707 29.997071h835.918368c16.598379 0 29.997071-13.398692 29.99707-29.997071 0-16.498389-13.398692-29.997071-29.99707-29.997071z"
                        fill="#FF6600" opacity=".502"></path>
                      <path
                        d="M705.931061 198.080656c3.099697 0 8.999121 0.799922 14.098624 5.899424l28.297236 28.297237c5.099502 5.099502 5.899424 10.998926 5.899424 14.098623 0 3.099697-0.799922 8.999121-5.899424 14.098623L392.161703 616.739772l-86.991505 28.997168 27.597305-82.791915 358.964945-358.964945c5.099502-5.199492 11.098916-5.899424 14.198613-5.899424m0-59.994141c-20.497998 0-40.896006 7.799238-56.594473 23.397715L281.672493 529.148325l-0.699932-0.699931-70.693096 212.079289 212.079289-70.693097 0.699932 0.699932 367.664095-367.664095c31.196953-31.196953 31.196953-81.892003 0-113.088956l-28.297237-28.297237c-15.598477-15.598477-35.996485-23.397715-56.494483-23.397715z"
                        fill="#FF6600"></path>
                      <path d="M578.626494 230.803461L621.049351 188.381603l141.40619 141.406191-42.421857 42.421857z"
                            fill="#FF6600"></path>
                    </svg>
                  </span>
                </div>
              </div>
            </div>

            <n-divider/>
          </div>
        </div>
      </div>
    </div>

    <el-dialog title="新建会话" v-model="open" width="600px" append-to-body>
      <el-form ref="aiChatConversationRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="对话标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入对话标题" />
        </el-form-item>
        <el-form-item label="模型标识" prop="model">
          <el-select
            v-model="form.modelId"
            placeholder="选择模型"
            style="width: 100%"
            @change="changeModel"
          >
            <el-option
              v-for="item in chatModelList"
              :key="item.id"
              :label="item.model"
              :value="item.id"
            />
          </el-select>
<!--          <el-input v-model="form.model" placeholder="请输入模型标识" />-->
        </el-form-item>
        <el-form-item label="最大 Token 数量" prop="maxTokens">
          <el-input v-model="form.maxTokens" placeholder="请输入单条回复的最大 Token 数量" />
        </el-form-item>
        <el-form-item label="最大 Message 数量" prop="maxContexts">
          <el-input v-model="form.maxContexts" placeholder="请输入上下文的最大 Message 数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>

import $ from "jquery";
const form = ref();
const rules = ref([]);
const open = ref(false);
const aiChatConversationRef =ref();
const { proxy } = getCurrentInstance();
const buttonLoading = ref(false);
const chatModelList = ref([])

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

const changeModel =(value)=>{
  let list = chatModelList.value.filter(item=>{
    return item.id === value
  })
  form.value.model = list[0].model
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  let modelRes = await listAiChatModel({});
  chatModelList.value = modelRes.rows
  open.value = true;
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    roleId: null,
    title: null,
    modelId: null,
    model: null,
    pinned: null,
    pinnedTime: null,
    systemMessage: null,
    temperature: null,
    maxTokens: null,
    maxContexts: null,
    creator: null,
    createTime: null,
    updater: null,
    updateTime: null,
    deleted: null,
    tenantId: null
  };
  proxy.resetForm("aiChatConversationRef");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["aiChatConversationRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateAiChatConversation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addAiChatConversation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

async function getList() {
  let response = await listAiChatConversation({});
  aiChatConversationList.value = response.rows
}

onMounted(async () => {
  if (!$common.isEmpty(store.id)) {
    await getList();
  }

  if ($common.mobile()) {
    $('.friend-aside').click(function () {
      showBodyLeft.value = true
      mobileRight()
    })
    $('.body-right').click(function () {
      showBodyLeft.value = false
      mobileRight()
    })
  }
  mobileRight()
  showEmail()

})
import { ref, reactive, onMounted, nextTick } from 'vue'
import { NAvatar, NTabs, NFormItemRow, NForm, NTabPane ,NInput, NBadge, NDivider, NButton, NModal, createDiscreteApi } from 'naive-ui'
import { ElMessage } from 'element-plus'
import * as $common from "@/utils/common"
import chat from '@/views/weblogFront/ai/compoents/chat.vue'
import groupInfo from '@/views/weblogFront/im/groupInfo.vue'
import useUserStore from "@/store/modules/user"
import { groups, currentGroupId, getImGroup, addGroupTopic, exitGroup, dissolveGroup } from "@/views/weblogFront/im/hooks/group"
import {emailVisible, email, code, password, codeString, getCode, submitDialog, showEmail} from "@/views/weblogFront/im/hooks/bindEmail"
import { changeData, changeType, changeModal, avatarType, avatarPrefix, showAvatarDialog, changeAvatar, changeDataType, submitAvatar, submitChange } from "@/views/weblogFront/im/hooks/changeData"
import { friendRequests, friends, currentFriendId, getImFriend, removeFriend, getFriendRequests, changeFriendStatus } from "@/views/weblogFront/im/hooks/friend"
import { showFriendCircle, treeHoleList, weiYanDialogVisible, isPublic, weiYanAvatar, weiYanUsername, pagination, launch, openFriendCircle, deleteTreeHole, submitWeiYan, pageWeiYan, cleanFriendCircle, addFriend } from "@/views/weblogFront/im/hooks/friendCircle"
import { systemMessages, showBodyLeft, imageList, changeAside, mobileRight, getSystemMessages, hiddenBodyLeft, imgShow, getImageList, parseMessage } from "@/views/weblogFront/im/hooks/imUtil"
import {isEmpty} from "@/utils/common";
import {getChatUserMessageListByUserId, listFriendMessage, setMessageRead} from "@/api/weblog/chatUserMessage";
import {creatGroupCommon, listChatGroup} from "@/api/weblog/chatGroup";
import { listAiChatMessage, getAiChatMessage, delAiChatMessage, addAiChatMessage, updateAiChatMessage } from "@/api/ai/aiChatMessage";
import { listAiChatConversation, getAiChatConversation, delAiChatConversation, addAiChatConversation, updateAiChatConversation } from "@/api/ai/aiChatConversation";
import aiCover from '@/assets/file/ai.jpeg'
import {listAiChatModel} from "@/api/ai/aiChatModel";




const { dialog } = createDiscreteApi(["dialog"])
const store = useUserStore()
// Reactive state
const aiChatMessageList = ref({})
const imMessageBadge = ref({})
const aiChatConversationList = ref([])
const currentAiChatConversation = ref(null)
const groupMessages = ref({})
const groupMessageBadge = ref({})
const groupChats = ref([])
const currentChatGroupId = ref(null)
const type = ref(1)
const subType = ref(1)
const showFriendValue = ref('')
const activeClass = reactive({
  imActive: false,
  friendActive: false,
  imGroupActive: false,
})
const currentActiveChat = ref(null)
const showAddDialog = ref(false);
const showCreateGroupDialog = ref(false);
const addTabName =ref("friend")
const addMessageId = ref(null);
const addMessageList = ref([]);
// Initialize IM
const im =ref("");
const createGroupForm = ref({})

const createGroupRules = ref( {
  id: [
    { required: true, message: "id不能为空", trigger: "blur" }
  ],
    groupName: [
    { required: true, message: "群名称不能为空", trigger: "blur" }
  ],
    masterUserId: [
    { required: true, message: "群主用户ID不能为空", trigger: "blur" }
  ],
    avatar: [
    { required: true, message: "群头像不能为空", trigger: "blur" }
  ],
    introduction: [
    { required: true, message: "简介不能为空", trigger: "blur" }
  ],
    notice: [
    { required: true, message: "公告不能为空", trigger: "blur" }
  ],
    inType: [
    { required: true, message: "进入方式[0:无需验证，1:需要群主或管理员同意]不能为空", trigger: "change" }
  ],
    groupType: [
    { required: true, message: "类型[1:聊天群，2:话题]不能为空", trigger: "change" }
  ],
})

function getWeiYan() {
  // Replace with axios if necessary
}

async function createGroupFu(){
  let response = await  creatGroupCommon(createGroupForm.value);
  closeCreateGroup();
  ElMessage.success("创建成功");
}



function closeCreateGroup(){
  createGroupForm.value ={};
  showCreateGroupDialog.value = false;
}

async function getFriendAndGroup() {
  await getImFriend()
  await getImGroup()
  await nextTick()
}


async function getHistoryMessage() {
  let response = await getChatUserMessageListByUserId({userId:store.id});
  aiChatMessageList.value = response.data
  aiChatConversationList.value = Object.keys(response.data)

  aiChatConversationList.value.forEach(item=>{
    imMessageBadge.value[item]=aiChatMessageList.value[item].filter(x=>{
      return x.messageStatus === 0 && x.toId === store.id
    }).length
  })
}

function sendMsg(msg, callback) {

}

function scrollToBottom() {
  nextTick(() => {
    const msgContainer = document.querySelector('.msg-container')
    if (msgContainer) {
      msgContainer.scrollTop = msgContainer.scrollHeight
    }
    imgShow()
  })
}

function   isActive(e, className, newType, newSubType, current, imType) {
  if (!isEmpty(newType)) {
    type.value = newType
    activeClass.imActive = newType === 1
    activeClass.friendActive = newType === 2
    activeClass.imGroupActive = newType === 3
  }

  if (newSubType !== undefined) {
    subType.value = newSubType
    if (newSubType === 4 && current) {
      currentFriendId.value = current.friendId
    }
    if (newSubType === 5 && current) {
      currentGroupId.value = current.id
    }
    if (newSubType === 2 && current && imType !== undefined) {
      if (imType === 1) {
        currentAiChatConversation.value = null
        currentChatGroupId.value = current
        groupMessageBadge.value[current] = 0
      } else if (imType === 2) {
        currentChatGroupId.value = null
        currentAiChatConversation.value = current
        setMessageRead({fromId:current,toId:store.id})
        imMessageBadge.value[current] = 0
      }
    }
    scrollToBottom()
  }

  currentActiveChat.value = e instanceof HTMLElement ? e : e.currentTarget
}



</script>




<style scoped>

.is-active-chat{
  background-color: #f3f3f3;
}

.friend-wrap {
  background: var(--imBackground) no-repeat center;
  background-size: 300% 300%;
  animation: gradientBG 100s ease infinite;
  width: 100vw;
  height: 100vh;
}

.friend-box {
  display: flex;
  background-color: var(--white);
  border-radius: 10px;
  position: absolute;
  width: calc(100vw - 40px);
  height:  calc(100vh - 40px);
  margin: 20px;
  //top: 60px;
  //left: 50%;
  //transform: translateX(-50%) translateY(-50%);
  overflow: hidden;
}

.friend-aside {
  width: 60px;
  border-right: 1px solid var(--maxLightGray);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.friend-bode {
  flex: 1;
  display: flex;
}

.body-left {
  width: 260px;
  box-shadow: 3px 0 6px var(--maxLightGray);
}

.body-right {
  flex: 1;
  position: relative;
}

.user-thumb {
  width: 36px;
  height: 36px;
  margin-top: 15px;
  margin-left: 12px;
  cursor: pointer;
}

.friend-chat {
  margin-top: 25px;
  text-align: center;
  cursor: pointer;
}

.friend-text {
  font-size: 13px;
}

.friend-set {
  text-align: center;
  margin-bottom: 20px;
  cursor: pointer;
}

.im-input {
  margin: 13px;
  width: 240px;
}

.im-user {
  display: flex;
  padding: 10px;
  cursor: pointer;
  height: 60px;
  box-sizing: border-box;
}

.im-user-group {
  display: flex;
  padding: 10px;
  cursor: pointer;
  height: 65px;
  box-sizing: border-box;
}

.im-active, .friend-active, .im-group {
  background: var(--imBG);
}

.im-user-right {
  flex: 1;
  margin-left: 20px;
}

.aside-list {
  height: calc(100% - 60px);
}

.im-down {
  margin-top: 3px;
  font-size: 12px;
  color: var(--greyFont);
}

.aside-active {
  color: var(--blue);
  font-weight: 800;
}

.im-friend {
  margin-left: 20px;
  align-self: center;
  font-size: 15px;
}

.body-left :deep(.n-divider .n-divider__title)  {
  color: var(--greyFont);
  font-size: 12px;
  letter-spacing: 2px;
}

.group-tag {
  border-radius: 2px;
  padding: 2px;
  background: var(--themeBackground);
  color: var(--white);
  margin-right: 12px;
}

.msg-one {
  margin: 15px 20px;
  display: flex;
  align-items: flex-start;
}

/* 滚动条 */
.friend-box ::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.friend-box ::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: var(--lowGray);
}

.sendMsg .n-button {
  height: 35px;
  padding: 15px 25px;
}

.system-date {
  font-size: 12px;
  color: var(--greyFont);
  margin-bottom: 5px;
}

.system-content {
  background-color: var(--messageColor);
  border-radius: 4px;
  max-width: 80%;
  padding: 5px 10px;
  line-height: 25px;
  word-break: break-all;
  color: var(--black);
}

.friend-request {
  background: var(--midWhite);
  overflow-y: scroll;
  height: calc(100% - 60px);
}

.request-status {
  font-size: 16px;
  color: var(--greyFont);
  flex: 1;
  display: flex;
  justify-content: right;
  align-items: center;
}

.friend-label {
  color: var(--greyFont);
  margin-right: 30px;
}

.friend-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 65%;
  padding-top: 50px;
}

.body-right .n-card.n-card--bordered {
  border: none;
}

#outerImg {
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 10;
  width: 100%;
  height: 100%;
  display: none;
}

.mobile-right::before {
  content: "👈";
  position: absolute;
  width: 100%;
  height: 100%;
  font-size: 40px;
  color: var(--white);
  top: 0;
  left: 0;
  background: var(--maxGreyFont);
  z-index: 100;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.pagination-wrap {
  display: flex;
  justify-content: center;
  height: 35px;
  margin-top: 15px;
  margin-bottom: 10px;
}

.treeHole-wrap {
  width: 800px;
  height: calc(100vh - 100px);
  overflow-y: scroll;
}

.treeHole-wrap::-webkit-scrollbar-thumb {
  background-color: var(--lowGray);
  border-radius: 5px;
}

.treeHole-wrap::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.weiyan-edit {
  width: 350px;
  background-color: var(--background);
  border-radius: 10px;
  padding: 20px;
}

.email-wrap {
  padding: 20px;
  background: var(--white);
  border-radius: 10px;
  transition: all 1s ease;
}

.email-title {
  line-height: 30px;
  font-size: 24px;
  margin-bottom: 15px;
}

@media screen and (max-width: 1200px) {
  .friend-box {
    width: 95vw;
    height: 95vh;
  }
}

@media screen and (max-width: 850px) {
  .friend-box {
    width: 100vw;
    height: 100vh;
    border-radius: unset;
  }

  .friend-bode {
    max-width: calc(100vw - 60px);
  }

  .body-right {
    max-width: calc(100vw - 60px);
  }

  .treeHole-wrap {
    width: calc(100vw - 40px);
  }
}

@media screen and (max-width: 400px) {
  .msg-one {
    margin: 15px 10px;
  }

  .friend-model {
    width: 90% !important;
  }
}
</style>
